<?php

/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2018/2/26
 * Time: 下午4:42
 */
class Bill_api extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('form_validation');//加载表单验证类库
        $this->load->helper('json');
        $this->load->helper('common');
        $this->load->model('user_model');
        $this->load->model('order_model');
        $this->load->model('customer_model');
        $this->load->model('bill_model');
        $this->load->library('email');
    }

    // 商城账期还款同步
    public function update_bill_status_api()
    {
        $post = $this->input->post();
        if (check_param($post, ['bill_bn', 'actual_repayment_date', 'time_stamp', 'token'])) {
            // 验签
            $token = create_token($post, $this->config->item("token_const"));
            $check_res = check_token($token, $post['token'], $post['time_stamp'], $this->config->item("time_out"));
            if ($check_res['status'] == -1) {
                send_json(array('code' => -1, 'data' => '', 'msg' => $check_res['msg']));
            }

            $upd['status'] = 1;
            $upd['actual_repayment_date'] = $post['actual_repayment_date'];
            $bool = $this->db->where(array("bill_bn" => $post['bill_bn']))->update('app_bill', $upd);
            if ($bool) {
                send_json(array('code' => 0, 'data' => '', 'msg' => "同步成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "同步失败"));
            }
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    // 提交账期付款申请 cj
    public function add_account_period_repayment_apply_api()
    {
        $post = $this->input->post();
        if (check_param($post, ['shop_user_id', 'bill_bn', 'receiver_name', 'receiver_email', 'time_stamp', 'token'])) {

            // 验签
            $token = create_token($post, $this->config->item("token_const"));
            $check_res = check_token($token, $post['token'], $post['time_stamp'], $this->config->item("time_out"));
            if ($check_res['status'] == -1) {
                send_json(array('code' => -1, 'data' => '', 'msg' => $check_res['msg']));
            }

            $customer_info = $this->user_model->user_detail_by_shop_user_id($post['shop_user_id']);
            $customer_id = $customer_info['id'];
            $send_name = $customer_info['name'];
            $send_email = $customer_info['email'];
            $bill_bn = $post['bill_bn'];
            $bill_id = $this->bill_model->bill_bn_to_bill_id($bill_bn);
            if (!$bill_id) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "没有此账单"));
            }
            $receiver_name = $post['receiver_name'];
            $receiver_email = $post['receiver_email'];
            $remark = isset($post['remark']) ? $post['remark'] : '';
            $insert_id = $this->bill_model->add_account_period_repayment_apply($customer_id, $bill_id, $receiver_name, $receiver_email, $send_name, $send_email, $remark);
            if ($insert_id) {
                // 发送邮件
                $sender_name = $send_name;
                $to_email = $receiver_email;
                $title = '提交账期付款申请';
                $id = encrypt($insert_id);
                $link = $this->config->item("base_url") . '/bill/insure_account_period_repayment_apply?apply_id=' . $id;
                $content = "您好，" . $receiver_name . "，这是账期编号为：" . $bill_bn . "的付款申请通知，请点击加密链接确认：\r\n {unwrap}<a href='$link' target='_blank'>点我确认</a>{/unwrap}";
                $res = $this->bill_model->send_email($sender_name, $to_email, $title, $content, $mailtype = 'html');
                if ($res) {
                    $this->db->where(array("id" => $insert_id))->update('app_account_period_repayment_apply', array('send_status' => 1));
                } else {
                    log_message('error', '发送邮件失败，内容为：' . $content);
                }

                send_json(array('code' => 0, 'data' => '', 'msg' => "添加成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "添加失败"));
            }

        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    //扣除账期额度
    public function amount_deductions()
    {
        $post = $this->input->post();
        if (check_param($post, ['money', 'shop_user_id', 'time_stamp', 'token'])) {
            // 验签
            $token = create_token($post, $this->config->item("token_const"));
            $check_res = check_token($token, $post['token'], $post['time_stamp'], $this->config->item("time_out"));
            if ($check_res['status'] == -1) {
                send_json(array('code' => -1, 'data' => '', 'msg' => $check_res['msg']));
            }

            //获取admin的customer_id
            $sql = 'select id,parent_id,identity from app_customer WHERE shop_user_id = ' . $post['shop_user_id'];
            $res = $this->db->query($sql)->row_array();
            if (!$res) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "用户不存在"));
            }
            $id = $this->customer_model->get_admin_customer_id($res['id']);


            $this->db->where(array('customer_id'=>$id));
            $this->db->set('account_period_quota_used',"account_period_quota_used +'".$post['money']."'",FALSE);
            $result = $this->db->update('app_admin');

            if ($result) {
                $data['customer_id'] = $res['id'];
                $data['order_bn'] = $post['order_bn'];
                $data['money'] = $post['money'];
                $data['created_at'] = date("Y-m-d H:i:s",time());
                $return_data = array('order_bn'=>$post['order_bn'],'pay_time'=>time());
                $this->db->insert('app_account_period_used_record', $data);

                if($res['identity'] != 1){
                    $where = array('customer_id'=>$res['id'],'month'=>date('Y-m',time()));
                    $row = $this->db->where($where)->from('app_budget')->get()->row_array();
                    if($row){
                        $this->db->where($where);
                        $this->db->set('used',"used +'".$post['money']."'",FALSE);
                        $result = $this->db->update('app_budget');
                    }else{
                        $where = array('customer_id'=>$res['id']);
                        $total_quota = $this->db->select('total_quota')->where($where)->from('app_manager_user')->get()->row_array();
                        $budget_arr = [];
                        $budget_arr['customer_id'] = $res['id'];
                        $budget_arr['budget'] = $total_quota['total_quota'];
                        $budget_arr['used'] = $post['money'];
                        $budget_arr['month'] = date("Y-m");
                        $this->db->insert('app_budget',$budget_arr);
                    }
                }

                send_json(array('code' => 0, 'data' => $return_data, 'msg' => "扣除成功",'url'=>$this->config->item("base_url")."order/common_order"));
            } else {
                send_json(array('code' => -1, 'data' => "", 'msg' => "扣除失败"));
            }
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    public function invoice_synchronous()
    {
        $post = $this->input->post();
        if (check_param($post, ['shop_user_id', 'shop_id','bill_bn','invoice_bn','invoice_money','invoice_pic', 'time_stamp', 'token'])) {
            // 验签
            $token = create_token($post, $this->config->item("token_const"));
            $check_res = check_token($token, $post['token'], $post['time_stamp'], $this->config->item("time_out"));
            if ($check_res['status'] == -1) {
                send_json(array('code' => -1, 'data' => '', 'msg' => $check_res['msg']));
            }

            //获取customer_id
            $sql = 'select id from app_customer WHERE shop_user_id = ' . $post['shop_user_id'];
            $customer = $this->db->query($sql)->row_array();
            if (!$customer) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "用户不存在"));
            }

            $sql = 'select invoice from app_invoice WHERE shop_id = ' . $post['shop_id'];
            $invoice = $this->db->query($sql)->row_array();
            if (!$customer) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "发票不存在"));
            }

            $data = array();
            $data['customer_id'] = $customer['id'];
            $data['invoice_id'] = $invoice['id'];
            $data['bill_bn'] = $post['bill_bn'];
            $data['invoice_bn'] = $post['invoice_bn'];
            $data['invoice_money'] = $post['invoice_money'];
            $data['invoice_pic'] = $post['invoice_pic'];
            $data['created_at'] = date("Y-m-d H:i:s",time());

            $sql = 'select id from app_bill_invoice WHERE invoice_bn = ' . $data['invoice_bn'] . ' ' ;
            $result = $this->db->query($sql)->row_array();
            if (!$result) {
                $bool = $this->db->insert("app_bill_invoice", $data);
            } else {
                $bool = $this->db->where(array("invoice_bn" => $data['invoice_bn']))->update('app_bill_invoice', $data);
            }

            if ($bool) {
                send_json(array('code' => 0, 'data' => '', 'msg' => "同步成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "同步失败"));
            }
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

}